package cn.edw.swu.bc.todolist

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log

class DBTodoHelper(
    context: Context?,
    name: String?,
    version: Int
) : SQLiteOpenHelper(context, name, null, version) {
    val TAG="@@dbhelper"
    override fun onCreate(db: SQLiteDatabase) {

        db.execSQL(
            "CREATE TABLE ${Todo.TABLE} (\n" +
                    "\t${Todo.COL_ID} integer PRIMARY KEY autoincrement,\n" +
                    "\t${Todo.COL_CONTENT} text,\n" +
                    "\t${Todo.COL_TIME} REAL)"
        )

    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {

    }

    @SuppressLint("Range")
    fun readInDb(): ArrayList<Todo> {
        val db = this.readableDatabase
        val cursor = db.query(
            Todo.TABLE, null, null, null, null, null,
            "${Todo.COL_TIME} desc "
        )
        val arr = arrayListOf<Todo>()
        if (cursor.moveToFirst()) {
            do {
                arr.add(
                    Todo(
                        cursor.getString(cursor.getColumnIndex(Todo.COL_CONTENT)),
                        cursor.getLong(cursor.getColumnIndex(Todo.COL_TIME)),
                    ).apply {
                        id = cursor.getInt(cursor.getColumnIndex(Todo.COL_ID))
                    }
                )
            } while (cursor.moveToNext())
        }
        cursor.close()
        return arr
    }

    fun insertInDb(text: String): Int {
        val db = this.writableDatabase
        val values = ContentValues().apply {
            put(Todo.COL_CONTENT, text)
            put(Todo.COL_TIME, System.currentTimeMillis())
        }
        return db.insert(Todo.TABLE, null, values).toInt()
    }

    fun delInDb(id: Int) {
        val db = this.writableDatabase
        Log.d(TAG,Todo.COL_ID + "=${id}")
        db.delete(Todo.TABLE, Todo.COL_ID + "=${id}", null)
    }
}